package com.specialprice.business;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import nimnaw.appengine.base.datastore.PMF;

import com.specialprice.model.Product;
import com.specialprice.model.ProductPrice;

public class ProductBusiness {

	private static final Logger log = Logger.getLogger(ProductBusiness.class
			.getName());

	public Product getProductById(long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			return pm.getObjectById(Product.class, id);
		} catch (JDOObjectNotFoundException e) {
			return null;
		} finally {
			pm.close();
		}
	}

	public List<ProductPrice> getPriceList(long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query q = pm.newQuery(ProductPrice.class);
		q.setFilter("id == idParam");
		q.declareParameters("Long idParam");

		try {

			@SuppressWarnings("unchecked")
			List<ProductPrice> ret = (List<ProductPrice>) q.execute(id);
			ret = (List<ProductPrice>) pm.detachCopyAll(ret);

			return ret;
		} finally {
			q.closeAll();
			pm.close();
		}
	}

	public Long[] getStaleProducts(Date date) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query q = pm.newQuery("select id from " + Product.class.getName());
		q.declareImports("import java.util.Date");
		q.declareParameters("Date timestampParam");
		q.setFilter("timestamp < timestampParam");

		try {
			@SuppressWarnings("unchecked")
			List<Long> ids = (List<Long>) q.execute(date);
			return ids.toArray(new Long[ids.size()]);
		} finally {
			q.closeAll();
			pm.close();
		}
	}

	public void deleteProduct(long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		Transaction tx = pm.currentTransaction();

		Query q = pm.newQuery(ProductPrice.class);
		q.setFilter("id == idParam");
		q.declareParameters("Long idParam");

		try {
			tx.begin();
			
			Product product = (Product) pm.getObjectById(Product.class, id);
			pm.deletePersistent(product);

			q.deletePersistentAll(id);
			
			tx.commit();
		} finally {
			q.closeAll();
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
	}
}
